<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header to="/disasterLosses" :back="true" />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item" v-if="index == 0">
          <!-- 次级标题 -->
          <CollapsibleTable :name="'各省（直辖市）抽样调查点数量统计'" />
        </div>
        <div class="app-left-item" v-if="index == 0">
          <!-- 次级标题 -->
          <subheadings :name="'县级行政区划调查点覆盖率'" />
          <CountyCoverage />
        </div>
        <div class="app-left-item" v-if="index == 0">
          <!-- 次级标题 -->
          <subheadings :name="'乡镇行政区划调查点覆盖率'" />
          <TownshipCoverage />
        </div>
        <div class="app-left-item buildItem" v-if="index == 1">
          <!-- 次级标题 -->
          <CollapsibleTable1 :index="1" v-if="index == 1" />
        </div>
        <div class="app-left-item riskPoint" v-if="index == 2">
          <!-- 次级标题 -->
          <CollapsibleTable1 :index="2" v-if="index == 2" />
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <headline :name="name[index]" />
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', left: '42px' }" />
          <button
            v-if="proviceFeature"
            style="position: absolute; right: 10px; top: 10px; z-index: 999"
            @click="goFull"
          >
            返回
          </button>
          <OlMap
            :doubleZoomDisable="true"
            :pinchZoomDisable="true"
            :refId="'disasterLosses'"
            style="height: 100%"
            @getMap="getMap"
            @mapClick="mapClick"
          ></OlMap>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="btnChange">
          <span :class="index == 0 ? 'activeBackground' : 'background'" @click="changeBtn(0)">抽样调查点</span>
          <span :class="index == 1 ? 'activeBackground' : 'background'" @click="changeBtn(1)">建筑物单体</span>
          <span :class="index == 2 ? 'activeBackground' : 'background'" @click="changeBtn(2)">灾害风险点</span>
        </div>
        <div class="app-right-item">
          <!-- 次级标题 -->
          <RightFirstEcharts :index="index" />
        </div>
        <div class="app-right-item">
          <!-- 次级标题 -->
          <RightSecondEcharts :index="index" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import CollapsibleTable from './components/CollapsibleTable';
import CollapsibleTable1 from './components/CollapsibleTable1';
import CountyCoverage from './components/CountyCoverage';
import TownshipCoverage from './components/TownshipCoverage';
import RightFirstEcharts from './components/RightFirstEcharts';
import RightSecondEcharts from './components/RightSecondEcharts';

import OlMap from '@/components/Olmap';
import { Style, Circle as CircleStyle, Fill, Stroke, Text, Icon } from 'ol/style';
import { Feature } from 'ol';
import { Point } from 'ol/geom';
import { Vector as VectorLayer } from 'ol/layer';
import { Cluster, Vector as VectorSource } from 'ol/source';
import { ref, reactive, defineProps } from 'vue';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import { getChinaBaseMap, getBaseDir } from '@/map/projMap.js';
import { getTileLayerByName, getProviceFeature } from '@/utils/matchProvince';
import { Util } from '@supermap/iclient-ol';
import { getSurveyPointCountMap } from '@/api/disasterLosess.js';

import point_single_img from '@/assets/map/image/newImage/single_icon.png';
import point_multi_img from '@/assets/map/image/newImage/multi_icon.png';
import { useRouter } from 'vue-router';
const router = useRouter();

const provinceLayer = ref(null);
const proviceFeature = ref(null);
const selectProvinceLayer = ref(null);
const data = reactive({
  index: 0, //默认下标1
  name: ['全国预评估现场抽样调查点分布图', '全国建筑物单体抽样调查分布图', '全国地震灾害风险点抽样调查分布图'],
});

const { index, name } = toRefs(data);

const changeBtn = (num) => {
  if (index.value == num) {
    return;
  }
  index.value = num;
  addSimpleLayer();
  // if (num == 0) {
  //   if (sampleLayer.value) {
  //     sampleLayer.value.setVisible(true);
  //   }
  //   if (riskLayer.value) {
  //     riskLayer.value.setVisible(false);
  //   }
  //   if (buildingLayer.value) {
  //     buildingLayer.value.setVisible(false);
  //   }
  // } else if (num == 1) {
  //   if (buildingLayer.value) {
  //     buildingLayer.value.setVisible(true);
  //   } else {
  //     addBuildingLayer();
  //   }
  //   if (riskLayer.value) {
  //     riskLayer.value.setVisible(false);
  //   }
  //   if (sampleLayer.value) {
  //     sampleLayer.value.setVisible(false);
  //   }
  // } else if (num == 2) {
  //   if (riskLayer.value) {
  //     riskLayer.value.setVisible(true);
  //   } else {
  //     addRiskLayer();
  //   }
  //   if (buildingLayer.value) {
  //     buildingLayer.value.setVisible(false);
  //   }
  //   if (sampleLayer.value) {
  //     sampleLayer.value.setVisible(false);
  //   }
  // }
};

const mapInstance = ref(null);
const sampleLayer = ref(null);
// const buildingLayer = ref(null);
// const riskLayer = ref(null);
const getMap = (map) => {
  mapInstance.value = map.value;
  console.log('jjj', mapInstance.value);

  addProvinceNameLayer();
  addSimpleLayer();
};
const mapClick = async (event) => {
  const clickedFeature = mapInstance.value.forEachFeatureAtPixel(event.pixel, (feature) => feature);
  console.log('click', clickedFeature);
  if (clickedFeature && clickedFeature.get('adcode')) {
    router.push({
      path: '/disasterLosses/samplingPoint/provincePreEvaluation',
      query: { code: clickedFeature.get('adcode'), provinceName: clickedFeature.get('name') },
    });
    return;
    // 获取点击的省份边界
    const provinceGeometry = clickedFeature.getGeometry();
    // 移除或隐藏其他省份图层
    // mapInstance.value.getLayers().forEach((layer) => {
    //   if (layer.get('type') == 'point') {
    //     if (index.value == 0) {
    //       sampleLayer.value?.setVisible(true);
    //       riskLayer.value?.setVisible(false);
    //       buildingLayer.value?.setVisible(false);
    //     } else if (index.value == 1) {
    //       sampleLayer.value?.setVisible(false);
    //       riskLayer.value?.setVisible(false);
    //       buildingLayer.value?.setVisible(true);
    //     } else if (index.value == 2) {
    //       sampleLayer.value?.setVisible(false);
    //       riskLayer.value?.setVisible(true);
    //       buildingLayer.value?.setVisible(false);
    //     }
    //   } else {
    //     layer.setVisible(false);
    //   }
    // });
    // let provinceName = clickedFeature.get('name');
    // proviceFeature.value = await getProviceFeature(provinceName);
    // selectProvinceLayer.value = await getTileLayerByName(provinceName);
    // selectProvinceLayer.value.setZIndex(1);
    // mapInstance.value.addLayer(selectProvinceLayer.value);
    // setMask();

    // // 计算放大后的视图范围
    // const provinceExtent = provinceGeometry.getExtent();
    // // 更新地图视图以显示具体的省份地图
    // mapInstance.value.getView().fit(provinceExtent, { padding: [20, 20, 20, 20], duration: 1000 }); // 1000毫秒的动画效果
  }
};
// const unSetMask = () => {
//   let layer;
//   switch (index.value) {
//     case 0:
//       layer = sampleLayer.value;
//       break;
//     case 1:
//       layer = buildingLayer.value;
//       break;
//     case 2:
//       layer = riskLayer.value;
//       break;
//   }
//   Util.unsetMask(layer);
// };
// const setMask = () => {
//   let layer;
//   switch (index.value) {
//     case 0:
//       layer = sampleLayer.value;
//       break;
//     case 1:
//       layer = buildingLayer.value;
//       break;
//     case 2:
//       layer = riskLayer.value;
//       break;
//   }
//   Util.setMask(layer, proviceFeature.value);
// };

function addProvinceNameLayer() {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  provinceLayer.value = new VectorLayer({
    source: geojsonSource,
    zIndex: 1,
    id: 'province',
    style: function (feature) {
      const textstyle = new Style({
        fill: new Fill({ color: 'transparent' }),
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#E1EFFF' }),
          text: feature.get('name'),
        }),
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(provinceLayer.value);
}
const addSimpleLayer = async () => {
  let markerSource = await getPointData();
  console.log('---=---', markerSource);
  if (sampleLayer.value) {
    sampleLayer.value.getSource().clear();
  }
  let _style = setClusterStyle();
  sampleLayer.value = new VectorLayer({
    source: markerSource,
    zIndex: 2,
    style: _style,
  });
  sampleLayer.value.set('type', 'point');
  mapInstance.value.addLayer(sampleLayer.value);
};
const getPointData = async () => {
  let _features = [];
  let res = await getSurveyPointCountMap({ flag: index.value });
  console.log('res---', res);
  if (res.code == 200 && res.data && res.data.length > 0) {
    const provinces = res.data;
    provinces.forEach((item) => {
      const point = new Feature({
        geometry: new Point([parseFloat(item.longitude), parseFloat(item.latitude)]),
      });

      const style = new Style({
        image: new Icon({
          src: point_single_img,
          anchor: [0.5, 0.5],
          scale: 0.6,
        }),
      });

      point.setStyle(style);
      _features.push(point);
    });
    console.log('_features---', _features);
  }
  let markerSource = new Cluster({
    distance: 50,
    source: new VectorSource({
      features: _features,
    }),
  });
  return markerSource;
};
const setClusterStyle = () => {
  const styleCache = {};
  const _style = (feature) => {
    const size = feature.get('features').length;
    let style = styleCache[size];
    if (!style) {
      if (size > 1) {
        style = new Style({
          image: new Icon({
            src: point_multi_img,
            anchor: [0.5, 0.5],
            scale: 0.6,
          }),
          text: new Text({
            text: size.toString(),
            font: 'bold 10px Calibri,sans-serif',
            fill: new Fill({ color: '#FF8900' }),
            offsetY: 0,
          }),
        });
      } else {
        style = new Style({
          image: new Icon({
            src: point_single_img,
            anchor: [0.5, 0.5],
            scale: 0.6,
          }),
        });
      }
      styleCache[size] = style;
    }
    return style;
  };
  return _style;
};

// function addBuildingLayer() {
//   let markerSource = addRandomPoints();
//   let _style = setClusterStyle();
//   buildingLayer.value = new VectorLayer({
//     source: markerSource,
//     zIndex: 2,
//     style: _style,
//   });
//   buildingLayer.value.set('type', 'point');
//   mapInstance.value.addLayer(buildingLayer.value);
// }

// function addRiskLayer() {
//   let markerSource = addRandomPoints();
//   let _style = setClusterStyle();
//   riskLayer.value = new VectorLayer({
//     source: markerSource,
//     zIndex: 2,
//     style: _style,
//   });
//   riskLayer.value.set('type', 'point');
//   mapInstance.value.addLayer(riskLayer.value);
// }
// const goFull = () => {
//   fetch(getBaseDir('China_4490.json'))
//     .then((response) => response.json()) // 将响应解析为 JSON 数据
//     .then((geojson) => {
//       // 使用 GeoJSON 格式解析器将数据转换为 Features
//       const geojsonFormat = new GeoJSonFormat();
//       let chinaBoundFeatures = geojsonFormat.readFeatures(geojson);
//       console.log('first', chinaBoundFeatures[0].getGeometry().getExtent());
//       let extent = chinaBoundFeatures[0].getGeometry().getExtent();
//       extent[1] = 0;
//       mapInstance.value.getView().fit(extent, { padding: [10, 20, 20, 20], duration: 1000 });
//     })
//     .catch((error) => {
//       console.error('Error fetching or processing GeoJSON:', error);
//     });
//   mapInstance.value.removeLayer(selectProvinceLayer.value);
//   mapInstance.value.getLayers().forEach((layer) => {
//     layer.setVisible(true);
//   });
//   unSetMask();
//   proviceFeature.value = null;
//   selectProvinceLayer.value = null;
// };
</script>

<style lang="scss" scoped>
.app-map {
  width: 960px;
  height: 100%;
  overflow: visible;
}

.app-main {
  display: flex;
  justify-content: space-between;

  .app-left {
    margin-left: 30px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;

    &-item {
      width: 450px;
      height: 300px;
      z-index: 100;
      // background: linear-gradient(135deg, #00032D 0%, #000C58 50%, #00032D 100%);
      // opacity: .85;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      color: #fff;

      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }

      &:nth-child(2) {
        height: 300px;
        z-index: 10;
      }

      &:nth-child(3) {
        height: 300px;
        z-index: 10;
      }
    }

    .riskPoint,
    .buildItem {
      height: 960px !important;
      z-index: 10;
    }
  }

  .app-right {
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;

    .btnChange {
      width: 450px;
      height: 40px;
      display: flex;
      justify-content: space-between;

      span {
        display: inline-block;
        width: 140px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        font-size: 20px;
        cursor: pointer;
      }

      .background {
        background: linear-gradient(0deg, #040c40 0%, #07145e 52%, #08268a 100%);
        border-radius: 4px 4px 4px 4px;
        opacity: 1;
        border: 1px solid #475adb;
        color: #475adb;
      }

      .activeBackground {
        position: relative;
        background: linear-gradient(0deg, #040c40 0%, #07145e 52%, #08268a 100%);
        border-radius: 4px 4px 4px 4px;
        opacity: 1;
        border: 1px solid #475adb;
        color: #46ffff;
      }

      .activeBackground:before {
        content: '';
        /* 声明伪元素 */
        position: absolute;
        /* 设置绝对位置 */
        left: 0%;
        /* 把三角形定位到矩形左边 */
        top: 0px;
        /* 让三角形垂直居中 */
        /* 设置让三角形中心位于矩形中心 */
        border-width: 5px;
        border-style: solid;
        border-color: #46ffff transparent transparent #46ffff;
      }
    }

    &-item {
      width: 450px;
      height: 430px;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;

      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }
    }
  }
}
</style>
